class MigrateCreateMessages < ActiveRecord::Migration
  class << self
    def up
      init_roles
      create_messages_table
      add_acl_data
    end

    def down
      init_roles
      delete_acl_data
      drop_messages_table
    end

    private
      #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      # Table create/drop methods
      #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
      def init_roles
        @@admin = Role.find(1)
      end

      def create_messages_table
        create_table_with_history(:messages, :force => true) do |t|
          t.column("title", :text, :null => false)
          t.column("details", :text, :null => false)
          t.column("page_id", :integer)
          t.column("expires_on", :datetime,:null => false)
          t.column("updated_by", :integer, :null => false)
          t.column("updated_at", :datetime)
        end

        foreign_key(:messages, :updated_by, :updaters)
        foreign_key(:messages, :page_id, :pages)
        create_lookup_table(:messages, :user_groups)
      end

      def drop_messages_table
        drop_lookup_table(:messages, :user_groups)
        drop_table_with_history(:messages)
      end

      def add_acl_data
        sobj = SystemObject.create(:name => "Message Management")
        @@admin.add_system_object(sobj)

        SystemMethod.create(:name => "manage/messages/list", :system_object_id => sobj.id)
        SystemMethod.create(:name => "manage/messages/create", :system_object_id => sobj.id)
        SystemMethod.create(:name => "manage/messages/show", :system_object_id => sobj.id)
        SystemMethod.create(:name => "manage/messages/update", :system_object_id => sobj.id)
        SystemMethod.create(:name => "manage/messages/delete", :system_object_id => sobj.id)

      end

      def delete_acl_data
        sobj = SystemObject.find(:first,:conditions => "name ='Message Management'")
        @@admin.delete_system_object(sobj)
        sobj.destroy
      end
  end #end class block
end
